//
//  MainViewController.m
//  Pink
//
//  Created by ZhongDaYunKe on 15/12/4.
//  Copyright © 2015年 ycy. All rights reserved.
//

#import "MainViewController.h"
#import "AddNewsView.h"
 #import "NewsSimpleView.h"
#import "NewsDetailViewController.h"
#import "PingTransition.h"
#import "PushNewsListViewController.h"
#import "UserCenterViewController.h"
#import "SetPushCountView.h"
#import "AppDelegate.h"
#import "SearchViewController.h"

@interface MainViewController ()

@property (nonatomic,strong)AddNewsView *addNews;
@property (nonatomic,strong)NSMutableArray *swipeDataSource;
@property (nonatomic,strong)SetPushCountView *setCountview;

@end

@implementation MainViewController

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    
}

- (void)setCountPress:(UIButton *)sender
{
    sender.selected = !sender.selected;
    
    if(sender.selected){
        [self.view addSubview:_setCountview];
        _setCountview.easeInEaseOut.alpha = 0.8;
    }else{
          [NSObject animate:^{
              _setCountview.easeInEaseOut.alpha = 0;
              
          } completion:^(BOOL finished) {
              [_setCountview removeFromSuperview];
              _setCountview.SetCount.text = 0;
          }];
    }
}

- (void)initNaviBar
{
    _setCountview = [[NSBundle mainBundle] loadNibNamed:@"SetPushCountView" owner:nil options:nil][0];
    _setCountview.frame = CGRectMake(10, 0, _setCountview.size.width, _setCountview.size.height);
    
    WS(weakself)
    UIButton *leftBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    leftBtn.frame = CGRectMake(0, 0, 20, 20);
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"setPushCount"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(setCountPress:) forControlEvents:UIControlEventTouchUpInside];
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:leftBtn];
    
    UIButton *rightBtn1 = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn1.frame = CGRectMake(0, 0, 20, 20);
    [rightBtn1 setBackgroundImage:[UIImage imageNamed:@"search"] forState:UIControlStateNormal];
    [rightBtn1 addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
        SearchViewController *vc = [[SearchViewController alloc] init];
        [weakself.navigationController pushViewController:vc animated:NO];
    }];
    
    
    UIButton *rightBtn2 = [UIButton buttonWithType:UIButtonTypeCustom];
    rightBtn2.frame = CGRectMake(0, 0, 20, 20);
    [rightBtn2 setBackgroundImage:[UIImage imageNamed:@"refresh"] forState:UIControlStateNormal];
    [rightBtn2 addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
        
    }];
 
    UIBarButtonItem *right1 = [[UIBarButtonItem alloc] initWithCustomView:rightBtn1];
    UIBarButtonItem *right2 = [[UIBarButtonItem alloc] initWithCustomView:rightBtn2];
    
    self.navigationItem.rightBarButtonItems = @[right2,right1];
    
        
}


-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSString *,id> *)change context:(void *)context
{
    
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor colorFromHexString:@"F3F0E9"];
    _swipeDataSource = [[NSMutableArray alloc] init];
    self.fromButton = [UIButton buttonWithType:UIButtonTypeCustom];
    [self initNaviBar];
    self.title = @"aaa";
    
    dispatch_async_on_main_queue(^{
        [self initSwipeView];
        [self initBottomView];
    });
    
    
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(swipeToLeft) name:@"swipeToLeft" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(swipeToRight) name:@"swipeToRight" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(goChatRoom) name:@"chatRoom" object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(pushToDetail:) name:@"pushToDetail" object:nil];
    [[AppDelegate shareAppdelegate] addObserver:self forKeyPath:@"selectTopic" options:NSKeyValueObservingOptionNew |NSKeyValueObservingOptionOld context:nil];
    
    
    
    WS(weakself)
    
    AVQuery *newsquery = [AVQuery queryWithClassName:@"News"];
    newsquery.cachePolicy = kAVCachePolicyNetworkElseCache;
    newsquery.maxCacheAge = 3600 * 72;
    [newsquery findObjectsInBackgroundWithBlock:^(NSArray *objects, NSError *error) {
       
        if (objects.count > 0) {
            [weakself.swipeDataSource removeAllObjects];
            [weakself.swipeDataSource addObjectsFromArray:objects];
            dispatch_async_on_main_queue(^{
                
                 [weakself.swipeableView loadViewsIfNeeded];
                
             });

            
        }else{
            
        }
        
    }];
    
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(imageDoneUpload) name:@"imageHasDoneUpload" object:nil];
    
}

- (void)initBottomView
{
    WS(weakself)
 
    UIButton *newsList = [UIButton buttonWithType:UIButtonTypeCustom];
    newsList.bounds = CGRectMake(0, 0, 54, 54);
    newsList.center = CGPointMake(self.view.size.width / 6, CGRectGetMaxY(_swipeableView.frame) + 40);
    [newsList setBackgroundImage:[UIImage imageNamed:@"newsList"] forState:UIControlStateNormal];
    [newsList addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
        
        _fromButton.center = CGPointMake(((UIButton *)sender).center.x, ((UIButton *)sender).center.y+64);
        PushNewsListViewController *vc = [[PushNewsListViewController alloc] init];
        [weakself.navigationController pushViewController:vc animated:YES];
        
        
    }];
    [self.view addSubview:newsList];
    
    
    UIButton *addNews = [UIButton buttonWithType:UIButtonTypeCustom];
    addNews.bounds = CGRectMake(0, 0, 62, 62);
    addNews.center = CGPointMake(self.view.size.width / 2, CGRectGetMaxY(_swipeableView.frame) + 40);
    [addNews setBackgroundImage:[UIImage imageNamed:@"addNews"] forState:UIControlStateNormal];
    
    [addNews addTarget:self action:@selector(addnewsClicked:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addNews];
    
    
    UIButton *userCenter = [UIButton buttonWithType:UIButtonTypeCustom];
    userCenter.bounds = CGRectMake(0, 0, 54, 54);
    userCenter.center = CGPointMake(self.view.size.width / 6 * 5, CGRectGetMaxY(_swipeableView.frame) + 40);
    [userCenter setBackgroundImage:[UIImage imageNamed:@"userCenter"] forState:UIControlStateNormal];
    [userCenter addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
        _fromButton.center = CGPointMake(((UIButton *)sender).center.x, ((UIButton *)sender).center.y+64);
        UserCenterViewController *vc =[[UserCenterViewController alloc] init];
        [weakself.navigationController pushViewController:vc animated:YES];
        
        
    }];
    [self.view addSubview:userCenter];
}


- (void)addnewsClicked:(UIButton *)sender
{
    
    
    
    
    
}

- (void)initSwipeView
{
    _swipeableView = [[ZLSwipeableView alloc] initWithFrame:CGRectZero];
    [self.view addSubview:_swipeableView];
     _swipeableView.dataSource = self;
    _swipeableView.delegate = self;
    _swipeableView.allowedDirection = ZLSwipeableViewDirectionLeft | ZLSwipeableViewDirectionRight;
     _swipeableView.numberOfActiveViews = 2;
     _swipeableView.frame = CGRectMake(35, 30, self.view.size.width - 70 ,self.view.size.height - 174);
   
    
 }

-(UIView *)nextViewForSwipeableView:(ZLSwipeableView *)swipeableView
{
    if (_swipeDataSource.count > 0) {
        News *newsobj = [News modelWithJSON:[AVClient RealDictionaryForObject:_swipeDataSource[0]]];
         [_swipeDataSource removeObjectAtIndex:0];
        NewsSimpleView *view = [[NewsSimpleView alloc] initWithFrame:swipeableView.bounds];
         view.newsObject = newsobj;
        view.backgroundColor = [UIColor whiteColor];
        
        dispatch_async_on_main_queue(^{
            [view initSubViews];
            [view initDatas];
        });
       
        return view;
        
    }else{
        return nil;
    }
   
}
-(void)swipeToLeft
{
    [_swipeableView swipeTopViewToLeft];
}
-(void)swipeToRight
{
    [_swipeableView swipeTopViewToRight];
}
-(void)goChatRoom
{
    
    NSLog(@"%@",((NewsSimpleView *)_swipeableView.topView).newsObject.title);
    
}

- (void)pushToDetail:(NSNotification *)notify
{
    NSLog(@"%@",notify.object);
    NewsDetailViewController *newsdetail = [[NewsDetailViewController alloc] initWithData:notify.object];
    [self.navigationController pushViewController:newsdetail animated:YES];
}


-(id<UIViewControllerAnimatedTransitioning>)navigationController:(UINavigationController *)navigationController animationControllerForOperation:(UINavigationControllerOperation)operation fromViewController:(UIViewController *)fromVC toViewController:(UIViewController *)toVC
{
    // Determine if we're presenting or dismissing
    
    if (operation == UINavigationControllerOperationPush) {
        
        PingTransition *ping = [[PingTransition alloc] initWithTransitionThroughButton:self.fromButton];
        return ping;
    }else{
        return nil;
    }

    
    
}

-(void)touchesEnded:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
     UITouch *touch = [touches anyObject];
    CGPoint apoint = [touch locationInView:self.view];
//    NSLog(@"%f,%f",apoint.x,apoint.y);
//    self.fromButton.bounds = CGRectMake(0, 0, 0, 0);
    self.fromButton.center= CGPointMake(apoint.x, apoint.y + 64);
    
}


- (void)addNewsMethod
{
    WS(weakSelf)
    _addNews = [[AddNewsView alloc] init];
    [_addNews initializeView];
    [self.view addSubview:_addNews];
    [_addNews mas_makeConstraints:^(MASConstraintMaker *make) {
        
        make.left.mas_equalTo(weakSelf.view.mas_left).offset(20);
        make.right.mas_equalTo(weakSelf.view.mas_right).offset(-20);
        make.top.mas_equalTo(weakSelf.view.mas_top).offset(30);
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom).offset(-80);
    }];
    
    UIButton *okAdd = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:okAdd];
    [okAdd setImage:[UIImage imageNamed:@"addnewsOK"] forState:UIControlStateNormal];
    [okAdd addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
        
        [_addNews uploadData];
        
    }];
    [okAdd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.right.mas_equalTo(weakSelf.view.mas_right).offset(-80);
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom).offset(-10);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    
    
    UIButton *CancelAdd = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:CancelAdd];
    [CancelAdd setImage:[UIImage imageNamed:@"addnewsNo"] forState:UIControlStateNormal];
    [CancelAdd addBlockForControlEvents:UIControlEventTouchUpInside block:^(id sender) {
        
    }];
    [CancelAdd mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.mas_equalTo(weakSelf.view.mas_left).offset(80);
        make.bottom.mas_equalTo(weakSelf.view.mas_bottom).offset(-10);
        make.size.mas_equalTo(CGSizeMake(60, 60));
    }];
    

}


- (void)imageDoneUpload
{
    
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
